package com.ego.auth.controller;

import com.ego.auth.properties.JwtProperties;
import com.ego.auth.service.AuthService;
import com.ego.common.pojo.CookieUtils;
import com.ego.entity.UserInfo;
import com.ego.user.pojo.User;
import com.ego.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {
    @Resource
    private AuthService authService;

    @Resource
    private JwtProperties prop;

    @PostMapping("/login")
    public ResponseEntity<Void> login(@RequestParam("username") String username,
                                      @RequestParam("password") String password,
                                      HttpServletRequest httpServletRequest,
                                      HttpServletResponse httpServletResponse
    ) {
        //查询对象是否存在
        User user = authService.checkUser(username, password);
        if (user == null){
            //不存在
            return  ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }else {
            try {
                String token = JwtUtils.generateToken(new UserInfo(user.getId(),user.getUsername()),prop.getPrivateKey(),5);
                CookieUtils.setCookie(httpServletRequest,httpServletResponse,prop.getCookieName(),token,prop.getCookieMaxAge()*60);
            } catch (Exception e) {
                log.error("授权失败",e);
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            return ResponseEntity.ok().build();

        }

    }

    /**
     * 验证用户信息
     * @param token
     * @return
     */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verifyUser(@CookieValue("EGO_TOKEN")String token,HttpServletRequest request, HttpServletResponse response){
        try {
            // 从token中解析token信息
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.prop.getPublicKey());
            // 解析成功要重新刷新token
            token = JwtUtils.generateToken(userInfo, this.prop.getPrivateKey(), this.prop.getExpire());
            // 更新cookie中的token
            CookieUtils.setCookie(request, response, this.prop.getCookieName(), token, this.prop.getCookieMaxAge());
            // 解析成功返回用户信息
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 出现异常则，响应500
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }


}
